<template lang="pug">
.view.cp-con-code-supply.fix-flex-pos
  //- 左边一级type
  .left-radio-warp.vertical-radio
    el-radio-group(v-model="firstType", @change="getDataSource", :class="{'single': allFirstType.length == 1}")
      el-radio-button(
          v-for="(item, index) in allFirstType",
          :key="index",
          :label="item.id") {{item.name}}
  //- 中间内容
  .mid-content-warp
    .material-table
      el-table(
        :data="tableList",
        height="100%",
        highlight-current-row,
        v-loading="loadingTable",
        size="mini",
        border)
        el-table-column(align="center", type="index", label="序号")
        el-table-column(align="center", label="位数")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit") {{scope.row.digits}}
            div(v-show="scope.row.canEdit")
              el-input(v-model="scope.row.digits")
        el-table-column(align="center", label="数据来源", min-width="160px")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit") {{scope.row.datasourceId | getText(dataSource)}}
            div(v-show="scope.row.canEdit")
              el-select(v-model="scope.row.datasourceId", placeholder="请选择")
                el-option(
                  v-for="(item, index) in dataSource",
                  :key="index",
                  :label="item.name",
                  :value="item.id")
        el-table-column(align="center", label="固定值", min-width="120px")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && scope.row.datasourceId==='fv'") {{scope.row.constant}}
            div(v-show="scope.row.canEdit && scope.row.datasourceId==='fv'")
              el-input(v-model="scope.row.constant")
        el-table-column(align="center", label="起始值")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snBeginning}}
            div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
              el-input(v-model="scope.row.snBeginning")
        el-table-column(align="center", label="截止值")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snEnding}}
            div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
              el-input(v-model="scope.row.snEnding")
        el-table-column(align="center", label="步长")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snStep}}
            div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
              el-input(v-model="scope.row.snStep")
        el-table-column(align="center", label="重置")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snCircular | getText(snCircularList)}}
            div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
              el-select(v-model="scope.row.snCircular", placeholder="请选择")
                el-option(
                  v-for="(item, index) in snCircularList",
                  :key="index",
                  :label="item.name",
                  :value="item.id")
        el-table-column(align="center", label="操作", min-width="96px")
          template(slot-scope="scope")
            div(v-show="!scope.row.canEdit && isEdit")
              i.icon-act.el-icon-edit(@click="editItem(scope.$index, scope.row)")
              i.icon-act.el-icon-plus(@click="addItem(scope.$index, scope.row)")
              i.icon-act.el-icon-delete(@click="deleteItem(scope.$index, scope.row)")
            div(v-show="scope.row.canEdit && isEdit")
              i.icon-act.el-icon-check(@click="saveEditItem(scope.$index, scope.row)")
              i.icon-act.el-icon-close(@click="cancelEditItem(scope.$index, scope.row)")
  //- 右边内容
  .right-content-warp
    .btn-wrap(v-show="!isEdit")
      el-button(type="primary", plain, @click="toEdit") 编辑
    .btn-wrap(v-show="isEdit")
      el-button(type="primary", plain, @click="submit") 确定
    .btn-wrap(v-show="isEdit")
      el-button(plain, @click="cancel") 取消
</template>

<script>
import ConfigApi from '@/api/config';

export default {
  name: 'condatasupply',
  data() {
    return {
      firstType: 0,
      allFirstType: [],
      loadingTable: true,
      tableList: [],
      dataSource: [],
      // 重置下拉框的选项
      snCircularList: [
        { id: 0, name: 'NO' },
        { id: 1, name: 'YES' }
      ],
      isEdit: false
    };
  },
  filters: {
    // 根据下拉框选项获取文本
    getText(id, list) {
      const target = list.find(item => item.id === id);
      if (target) {
        return target.name;
      }
      return null;
    },
  },
  created() {
    // 缓存编辑数据
    this.dataCache = [...this.tableList];
  },
  mounted() {
    // 取得编码器列表
    ConfigApi.getConCodeList().then((res) => {
      if (!res.status && res.obj.length) {
        this.allFirstType = res.obj;
        this.firstType = this.allFirstType[0].id;
        this.loadingTable = false;
        this.getDataSource(this.firstType);
      } else {
        this.$message.error(res.comment || '获取数据失败');
        this.loadingTable = false;
      }
    });
  },
  methods: {
    getDataSource(id) {
      this.loadingTable = true;
      this.isEdit = false;
      // 编码器数据来源列表
      ConfigApi.getCodeDataSource({ coder: id }).then((res) => {
        if (!res.status && res.obj) {
          this.dataSource = res.obj.dataSources;
          this.getCodeDetail();
        } else {
          this.$message.error(res.comment || '获取数据失败');
          this.loadingTable = false;
        }
      });
    },
    // 编码器详情
    getCodeDetail() {
      ConfigApi.getConCodeDetail({ id: this.firstType }).then((res) => {
        if (!res.status && res.obj) {
          this.tableList = res.obj.components;
          this.loadingTable = false;
        } else {
          this.tableList = [];
          this.$message.error(res.comment || '获取详情失败');
          this.loadingTable = false;
        }
      }).catch((error) => {
        this.$message.error('获取详情失败');
        this.loadingTable = false;
        console.log(JSON.stringify(error));
      });
    },
    toEdit() {
      this.tableCache = [...this.tableList];
      this.dataCache = [...this.tableList];
      // 初始化列表
      if (!this.tableList.length) {
        this.tableList = [{ canEdit: false }];
      }
      this.isEdit = true;
    },
    // 验证输入数据
    validateParam(data = []) {
      let needDigits = false;
      let needDataSource = false;
      let needSave = false;
      data.forEach((item) => {
        if (item.canEdit) {
          needSave = true;
        }
        if (!item.digits && item.digits !== 0) {
          needDigits = true;
        }
        if (!item.datasourceId && item.datasourceId !== 0) {
          needDataSource = true;
        }
      });
      return {
        needSave,
        needDigits,
        needDataSource
      };
    },
    submit() {
      const { needSave, needDigits, needDataSource } = this.validateParam(this.tableList);
      if (needDigits) {
        this.$message({ message: '请输入位数', type: 'warning' });
        return;
      }
      if (needDataSource) {
        this.$message({ message: '请选择数据来源', type: 'warning' });
        return;
      }
      if (needSave) {
        this.$message({ message: '请先保存编辑', type: 'warning' });
        return;
      }
      this.loadingTable = true;
      const params = { coder: this.firstType, encodingRecords: this.tableList };
      ConfigApi.submitConCodeDetail(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '保存成功', type: 'success' });
          this.isEdit = false;
          this.loadingTable = false;
        } else {
          this.loadingTable = false;
          this.$message.error(res.comment || '保存失败');
        }
      }).catch((error) => {
        this.$message.error('网络不给力，请稍后再试');
        this.loadingTable = false;
        console.log(JSON.stringify(error));
      });
    },
    cancel() {
      this.tableList = [...this.tableCache];
      this.isEdit = false;
    },
    /* ****** 表格操作  ****** */
    // 编辑
    editItem(index) {
      this.dataCache[index] = Object.assign({}, this.tableList[index]);
      this.$set(this.tableList[index], 'canEdit', true);
    },
    // 新增
    addItem(index) {
      this.tableList.splice((index + 1), 0, { state: 0, canEdit: true });
      this.dataCache.splice((index + 1), 0, { state: 0, canEdit: true, fromAdd: true });
    },
    // 删除
    deleteItem(index) {
      this.tableList.splice(index, 1);
    },
    // 保存
    saveEditItem(index) {
      this.tableList[index].canEdit = false;
    },
    // 取消
    cancelEditItem(index) {
      const cache = Object.assign({}, this.dataCache[index], { canEdit: false });
      if (cache.fromAdd) {
        // 新增时取消
        this.tableList.splice(index, 1);
        this.dataCache.splice(index, 1);
      } else {
        // 编辑时取消
        this.tableList.splice(index, 1, cache);
        this.tableList[index].canEdit = false;
      }
    }
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
.cp-con-code-supply
  overflow-x: hidden
  overflow-y: auto
  background: $THEMECOLOR
  padding: 20px 0 20px 20px
  height: 100%
  display: flex
  flex: 1
  .material-table
    height: 100%
  .el-radio-button
    display: block
  .left-radio-warp
    flex: 0 0 140px
    overflow-x: hidden
    overflow-y: scroll
    .el-radio-button__inner
      width: 120px
  .vertical-radio
    .el-radio-button .el-radio-button__inner
      border-left: 1px solid #dcdfe6
      border-bottom-width: 0
    .el-radio-button__orig-radio:checked+.el-radio-button__inner
      border-color: #409EFF
    .el-radio-button:first-child .el-radio-button__inner
      border-radius: 4px 4px 0 0
    .el-radio-button:last-child .el-radio-button__inner
      border-radius: 0 0 4px 4px
      border-bottom-width: 1px
    .single
      .el-radio-button:first-child .el-radio-button__inner,
      .el-radio-button:last-child .el-radio-button__inner
        border-radius: 4px 4px 4px 4px
  .mid-content-warp
    width: calc(100% - 240px)
    flex: 1
    padding-left: 20px
  .right-content-warp
    flex: 0 0 100px
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
  .btn-wrap
    text-align: center
    padding: 10px 0
</style>
